/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bry.cybercafe.optionstationmanager;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collections;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import javax.swing.DefaultListSelectionModel;
import javax.swing.table.DefaultTableModel;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;
import org.openide.util.NbPreferences;
import org.openide.windows.IOProvider;
import org.openide.windows.InputOutput;


public class StationManagerPanel extends javax.swing.JPanel implements ActionListener{

    private final StationManagerOptionsPanelController controller;
    private DialogDescriptor d = null;
    private StationPanel stationPanel = null;
    private InputOutput io = IOProvider.getDefault().getIO("DEBUG", true);
    private DefaultTableModel _model = null;
    private static Logger log = Logger.getLogger(StationManagerPanel.class.getName());
    
    StationManagerPanel(StationManagerOptionsPanelController controller) {
        this.controller = controller;
        initComponents();
                io.select();
                io.getOut().println("CREATED");
//                io.getOut().close();
        // TODO listen to changes in form fields and call controller.changed()
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new StationTableList();
        btnAdd = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();
        btnUpdate = new javax.swing.JButton();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Station No.", "Status"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(jTable1);

        btnAdd.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(btnAdd, "ADD STATION");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        btnDelete.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(btnDelete, "DELETE STATION");
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });

        btnUpdate.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(btnUpdate, "UPDATE STATION");
        btnUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUpdateActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 557, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnUpdate)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnDelete, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 253, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(btnDelete, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnAdd, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnUpdate, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(98, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    // <editor-fold defaultstate="collapsed" desc="click add">
    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        stationPanel = new StationPanel();
        d = new DialogDescriptor(stationPanel, "Add Station", true, this);
        d.setClosingOptions(new Object[]{});
        DialogDisplayer.getDefault().notify(d);
        
        
//        Handler handler = java.util.logging.FileHandler;
//        FileHandler f = new FileHandler
//        LogManager logManager = LogManager.getLogManager();
//        logManager.
        
        log.severe("HELLO WORLD");
//        LogManager.getLogManager().
//        LogManager logManager = LogManager.getLogManager();
//        for(String name : Collections.list(logManager.getLoggerNames())) {
//            io.getOut().println(name);
//        }
    }//GEN-LAST:event_btnAddActionPerformed
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="click update">
    private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdateActionPerformed
        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
        if(jTable1.getSelectedRow() >= 0) {
            stationPanel = new StationPanel();
            stationPanel.setStationNo(model.getValueAt(jTable1.getSelectedRow(), 0).toString());
            stationPanel.setStationStatus(model.getValueAt(jTable1.getSelectedRow(), 1).toString());
            d = new DialogDescriptor(stationPanel, "Update Station", true, this);
            d.setClosingOptions(new Object[]{});
            Object ret = DialogDisplayer.getDefault().notify(d);
            if(DialogDescriptor.OK_OPTION.equals(ret)) {
                io.getOut().println("UPDATED");
            } else {
                io.getOut().println("NOT UPDATED");
            }
   	        // 

        }
    }//GEN-LAST:event_btnUpdateActionPerformed
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="click delete">
    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
        if(jTable1.getSelectedRow() >= 0) {
            NbPreferences.forModule(StationManagerPanel.class).remove("stationNo"+jTable1.getSelectedRow());
            NbPreferences.forModule(StationManagerPanel.class).remove("stationStatus"+jTable1.getSelectedRow());
            model.removeRow(jTable1.getSelectedRow());
            log.log(Level.OFF, "Click Update");
        }
    }//GEN-LAST:event_btnDeleteActionPerformed
// </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="load">
    void load() {
        if(this._model == null) {
            jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {

                },
                new String [] {
                    "Station No.", "Status"
                }
            ) {
                boolean[] canEdit = new boolean [] {
                    false, false
                };

                public boolean isCellEditable(int rowIndex, int columnIndex) {
                    return canEdit [columnIndex];
                }
            });
            _model = (DefaultTableModel) jTable1.getModel();
            jTable1.setSelectionMode(DefaultListSelectionModel.SINGLE_SELECTION);
            int cntr = 0;
            while(true) {
                if("".equals(NbPreferences.forModule(StationManagerPanel.class).get("stationNo"+cntr, "")) ) {
                    break;
                } else {
                    _model.addRow(new String []{NbPreferences.forModule(StationManagerPanel.class).get("stationNo"+cntr, ""),
                    NbPreferences.forModule(StationManagerPanel.class).get("stationStatus"+cntr, "")});
                }
                cntr++;
            }
            jTable1.setModel(_model);
        }    
    }// </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="store">
    void store() {
        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
        for(int i = 0; i < model.getRowCount(); i++) {
            NbPreferences.forModule(StationManagerPanel.class).put("stationNo"+i,model.getValueAt(i, 0).toString());
            NbPreferences.forModule(StationManagerPanel.class).put("stationStatus"+i,model.getValueAt(i, 1).toString());
        }
    }// </editor-fold>

    boolean valid() {
        // TODO check whether form is consistent and complete
        return true;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnUpdate;
    private javax.swing.JScrollPane jScrollPane1;
    public javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables

    
    // <editor-fold defaultstate="collapsed" desc="click ok of station panel">
    @Override
    public void actionPerformed(ActionEvent e) {
        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
        if(e.getSource() == DialogDescriptor.CANCEL_OPTION) {
//        LifecycleManager.getDefault().exit();
          d.setClosingOptions(null);
        } else {
            if(!"".equals(stationPanel.getStationNo())) {
                if("Add Station".equals(d.getTitle())) {
                    model.addRow(new String []{stationPanel.getStationNo(),stationPanel.getStationStatus()});
                    jTable1.setModel(model);    
                } else {
                    model.setValueAt(stationPanel.getStationNo(), jTable1.getSelectedRow(), 0);
                    model.setValueAt(stationPanel.getStationStatus(), jTable1.getSelectedRow(), 1);
                }

//                io.select();
//                io.getOut().println(stationPanel.getStationStatus());
//                io.getOut().close();
                d.setClosingOptions(null);
            } else {
                
            }
//            if(!SecurityManager.login(stationPanel.getUsername(), panel.getPassword())) {
//            stationPanel.setInfo("Wrong user name or password");
//            } else {
//            d.setClosingOptions(null);
//            }
        }
    }// </editor-fold>
}
